package goerl

var registerNodeMap map[string]*Node
var registerNode *Node

func init() {
	registerNodeMap = make(map[string]*Node)
	registerNode = NewNode(recvRegisterMail)
	registerNode.Start()
}

//Register 根据一个名字注册并发节点
func Register(name string, node *Node) chan bool {
	var isOK chan bool
	isOK = make(chan bool)
	Send(registerNode, []interface{}{":Register", name, node, isOK})
	return isOK
}

//UnRegister 取消注册并发节点
func UnRegister(name string) {
	Send(registerNode, []interface{}{":UnRegister", name})
}

func GetNode(name string) *Node {
	return registerNodeMap[name]
}

func recvRegisterMail(msg interface{}) {
	msgData := msg.([]interface{})
	opt := msgData[0].(string)
	name := msgData[1].(string)
	var node *Node
	if len(msgData) > 2 {
		node = msgData[2].(*Node)
	}
	var isOK chan bool
	if len(msgData) > 3 {
		isOK = msgData[3].(chan bool)
	}

	switch opt {
	case ":Register":
		registerNodeMap[name] = node
		node.registerName = name
		isOK <- true
	case ":UnRegister":
		delete(registerNodeMap, name)
		node.registerName = ""
	}
}
